'''
Created on 2010/5/2

@author: Daniel
'''
from lxml import etree
from StringIO import StringIO

class ParserBoxScore:
    """
    """
    def __init__(self, html):
        """Parser2
        
        """
        root = etree.parse(StringIO(html), etree.HTMLParser()).getroot()
        self.teamBoxScoreNode = root.xpath('//*[@id="ysp-boxscore-mlb"]//*[@class="ysp-dynamic"]')[0]      
        self.gameBoxScoreNode = root.xpath('//*[@id="ysp-boxscore-mlb"]//*[@class="ysp-dynamic"]')[1]
        self.teamBoxScore = []
        self.gameBoxScore = []
    def run(self):
        self.processTeamBoxScore()
        self.processGameBoxScore()
                
    def _test(self, root):
        print len(root), [x.tag for x in root.iterchildren()]    
    
    def show(self):
        """
        """
        print self.teamBoxScore
        print self.gameBoxScore
        
    def processTeamBoxScore(self):
        """ process Team BoxScore
        generate self.teamBoxScore     ex. (result,title,away,home,others)
        """
        teamResultNode = self.teamBoxScoreNode.xpath('//*[@class="yspsctnhdln"]')[0]       
        awayStandings = self.teamBoxScoreNode.xpath('//div[@class="yspscores"]')[0].text
        homeStandings = self.teamBoxScoreNode.xpath('//div[@class="yspscores"]')[1].text
       
        result = ((teamResultNode[0].text, teamResultNode[0].tail.split(',')[0].strip(), homeStandings),
                  (teamResultNode[1].text, teamResultNode[1].tail.split(',')[0].strip(), awayStandings))       
        #print result
        games = len(self.teamBoxScoreNode.xpath('table[3]//tr[1]/td[2]/table//tr/td/table//tr/td/table//tr[2]/td[@class="yspscores"]'))-4
        #print games
        title = []
        title.extend(['Final'])
        title.extend([`x` for x in range(1, games+1)])
        title.extend(['H','R','E'])
        #print title
        boxAwayNode = self.teamBoxScoreNode.xpath('//tr[@class="ysptblclbg5"]')[0]
        away = []
        away.extend([boxAwayNode[1][0][0].text])
        away.extend([boxAwayNode[i].text for i in range(2,2+games)])
        away.extend([boxAwayNode[i][0].text for i in range(2+games,2+games+3)])
        #print away      
        boxHome = self.teamBoxScoreNode.xpath('//tr[@class="ysptblclbg5"]')[1]
        home = []
        home.extend([boxHome[1][0][0].text])
        home.extend([boxHome[i].text for i in range(2,2+games)])
        home.extend([boxHome[i][0].text for i in range(2+games,2+games+3)])
        #print home
        boxOthersNode = self.teamBoxScoreNode.xpath('table[3]//tr/td[2]/table//tr/td/table//tr/td/table//tr[9]/td/a')       
        others = [('WP', boxOthersNode[0].text, boxOthersNode[0].tail.split('\n')[0].strip())]
        i = 1
        if len(boxOthersNode) == 3:
            others.append((('S', boxOthersNode[1].text, boxOthersNode[1].tail.strip())))
            i += 1
        others.append(('LP', boxOthersNode[i].text, boxOthersNode[i].tail.strip()))
        #print others
        self.teamBoxScore = [result,tuple(title),tuple(away),tuple(home),tuple(others)]
        #print self.teamBoxScore

    def processGameBoxScore(self):
        """process Game Boxscore
        generate self.gameBoxScore
        """
        def _procoessSummary(subNode):
            """
            """
            title = 'Scoring Summary'
            flag = 0
            summary = [title]
            for item in subNode:
                subitem = item.xpath('td[@class="yspdetailttl"]')
                if len(subitem) == 1:
                    summary.append(subitem[0].text.split('\n')[1].strip())
                else:
                    subitem = item.xpath('td[@class="yspplaytext"]')
                    if len(subitem) == 1:
                        summary.append(subitem[0].text.split('\n')[1].strip())
            return summary
        
        def _processFielderBoxScore(node):
            """process player boxscore
            @return: 
            """
            player_count = len(node)-3
            team = node[0][0].text.strip()
            title = ('PLAYER','AB','R','H','RBI','HR','BB','K','SB','LOB','Season Avg')
            player = []
            def _processPlayer(subNode):
                """
                """
                p = []
                p.append((subNode[0][0].text,subNode[0][0].tail.strip()))
                for i in range(10):
                    p.append(subNode[i+1].text)
                player.append(p)            
            
            for i in range(player_count):
                _processPlayer(node[i+2])
            total = [x.text for x in node[-1][1:-1]]
            
            return {'Title':title, 'Team':team, 'Player':player, 'Total':total}
        
        def _processFielderOthers(node):
            """process player others
            @return: 
            """ 
            #print len(node[0]),node[0].tag                   
            battingNode = node[0][0][0]
            baseRunningNode=None
            fieldingNode=None
            if (len(node[0]) == 3):
                if len(node[0][2])== 2:                
                    baseRunningNode = node[0][2][0]
                    fieldingNode = node[0][2][1]
                elif len(node[0][2])== 1:
                    if node[0][2].xpath('table/tr/td[@class="yspdetailttl"]')[0].text == 'Fielding':
                        fieldingNode = node[0][2][0]                        
                    else:     
                        baseRunningNode = node[0][2][0]                        
                    
                else:
                    pass 
                  
            def _processDetail(subNode):
                l = []
                for i in range(1, len(subNode), 2):
                    l.append((subNode[i][0][0].text, subNode[i][0][0].tail.split('.')[0]))
                return l
            batting = _processDetail(battingNode)
            #print batting
            baseRunning=""
            if baseRunningNode != None:
                baseRunning = _processDetail(baseRunningNode)
            #print baseRunning
            fielding=""
            if fieldingNode != None:
                fielding = _processDetail(fieldingNode)
            #print fielding
            return {'Batting':batting, 'Base Running':baseRunning, 'Fielding':fielding}        
        
        def _processPitcherBoxScore(node):
            """
            @return: list
            """
            def _processPitcherScore(subNode):
                """
                """
                p = []
                p.append((subNode[0][0].text,subNode[0][0].tail))
                for i in range(9):
                    p.append(subNode[i+1].text)                                
                return p                                            

            title = ('PLAYER','IP','H','R','ER','BB','K','HR','WHIP','Season ERA')
            listTeam = node.xpath('tr/td[@class="ysptblhdr"]')
            away = listTeam[0].text.strip()
            home = listTeam[1].text.strip()
            awayPitcher = []
            homePitcher = []
            flag = 0
            for i in range(len(node)):
                count = len(node[i])
                #print count
                if flag == 2 and count == 11:
                    awayPitcher.append(_processPitcherScore(node[i]))
                elif flag == 5 and count == 11:
                    homePitcher.append(_processPitcherScore(node[i]))
                else:                     
                    flag += 1
            return {'Title':title, 'Away':(away,awayPitcher),'Home':(home,homePitcher)}
            
        def _processPitcherOthers(node):
            """
            @return: list
            """
            others = []
            listOthers = node.xpath('tr/td[@class="yspscores"]/b')            
            for item in listOthers:
                others.append((item.text, item.tail.split('.')[0]))                
            return others
        
        def _processGameDetail(node):
            """
            @return: list
            """
            listgameDetail = node.xpath('tr/td[@class="yspscores"]/b')
            return [listgameDetail[0].text, listgameDetail[0].tail]
        
        self.gameBoxScore = {}
        node = self.gameBoxScoreNode.xpath('table')
        summaryNode = node[1] 
        #self.gameBoxScore.append(_procoessSummary(summaryNode))
        self.gameBoxScore['Summary'] = _procoessSummary(summaryNode)
        awayBoxNode = node[3]
        #self.gameBoxScore.append(_processFielderBoxScore(awayBoxNode))
        self.gameBoxScore['AwayFielderBoxScore'] = _processFielderBoxScore(awayBoxNode)
        awayBoxOthersNode = node[5]
        #self.gameBoxScore.append(_processFielderOthers(awayBoxOthersNode))        
        self.gameBoxScore['AwayFielderOthers'] = _processFielderOthers(awayBoxOthersNode)
        homeBoxNode = node[7]
        #self.gameBoxScore.append(_processFielderBoxScore(homeBoxNode)) 
        self.gameBoxScore['HomeFielderBoxScore'] = _processFielderBoxScore(homeBoxNode)       
        homeBoxOthersNode = node[9]
        #self.gameBoxScore.append(_processFielderOthers(homeBoxOthersNode))        
        self.gameBoxScore['HomeFielderOthers'] = _processFielderOthers(homeBoxOthersNode)
        pitcherBoxNode = node[11]
        #self.gameBoxScore.append(_processPitcherBoxScore(pitcherBoxNode))
        self.gameBoxScore['PitcherBoxScore'] = _processPitcherBoxScore(pitcherBoxNode)
        pitcherBoxOthersNode = node[12]
        #self.gameBoxScore.append(_processPitcherOthers(pitcherBoxOthersNode))
        self.gameBoxScore['PitcherOthers'] = _processPitcherOthers(pitcherBoxOthersNode)
        gameDetailsNode = node[13]        
        #self.gameBoxScore.append(_processPitcherOthers(gameDetailsNode))
        self.gameBoxScore['GameDetail'] = _processGameDetail(gameDetailsNode)
        #for key,value in self.gameBoxScore.iteritems():
        #    print key,value
    
if __name__ == '__main__':
    """test   
    """
    from urllib import urlopen
    gid = '300503118'
    url = "http://sports.yahoo.com/mlb/boxscore?gid=%s" % gid    
    f = urlopen(url)
    html = f.read()
    p = ParserBoxScore(html)
    p.run()
    p.show()
    
    